# coding:utf-8

from sqlalchemy import Column, extract, and_
from sqlalchemy.types import Integer, BIGINT, VARCHAR

from app_admin.extensions.mysql.mysql_base import Base
from ..extensions.mysql.session import sessionCM


class MPayRecord(Base):
    __tablename__ = 'ibb_pay_record'

    _id = Column(Integer, autoincrement=True, nullable=False, unique=True, primary_key=True)
    target_user_id = Column(Integer, nullable=False)
    target_user_name = Column(VARCHAR(255), index=True)  # or Column(String(30))
    source_user_id = Column(Integer, nullable=False)
    pay_gold = Column(BIGINT, nullable=False)
    pay_type = Column(Integer, default=0)

    def __init__(self, target_user_id,target_user_name, source_user_id, pay_gold, pay_type):
        self.target_user_id = target_user_id
        self.target_user_name = target_user_name
        self.source_user_id = source_user_id
        self.pay_gold = pay_gold
        self.pay_type = pay_type

    def to_dict(self):
        return {"id": self._id, "target_user_id": self.target_user_id,
                "target_user_name": self.target_user_name, "source_user_id": self.source_user_id,
                "pay_gold": self.pay_gold, "pay_type": self.pay_type}

    @classmethod
    def create_pay_record(cls, target_user_id, target_user_name, pay_gold, pay_type, source_user_id):
        with sessionCM() as session:
            new_record = cls(target_user_id,target_user_name, source_user_id, pay_gold, pay_type)
            session.add(new_record)
            session.commit()
            return 1

    @classmethod
    def query_record_by_page(cls, page, size=20):
        with sessionCM() as session:
            records = session.query(MPayRecord).all()
            ret = []
            for i in records:
                ret.append(i.to_dict())
            return ret if records else []


    @classmethod
    def get_pay_num_by_user_and_date(cls, username, date):
        with sessionCM() as session:
            pay_num = session.query(MPayRecord).filter(extract('month', MPayRecord.created_date) == 12)
            stmt = session.query(MPayRecord).filter(and_(MPayRecord.created_date >= start_time, MPayRecord.created_date <= end_time)).all()